package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron="0 * * * * ?")
    public void time_Order(){
        log.info("检查超时订单{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> timeOrderAndLT = orderMapper.getTimeOrderAndLT(Orders.PENDING_PAYMENT, time);
        if(timeOrderAndLT!=null && !timeOrderAndLT.isEmpty()){
            for (Orders orders : timeOrderAndLT) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时取消");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
    @Scheduled(cron="0 0 1 * * ?")
    public void endOrders(){
    log.info("自动完成已送达订单{}", LocalDateTime.now());
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.getTimeOrderAndLT(Orders.DELIVERY_IN_PROGRESS, localDateTime);
        if(orders!=null && !orders.isEmpty()){
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(order.getEstimatedDeliveryTime());
                orderMapper.update(order);
            }
        }
    }
}
